package com.itheima.appserver.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.commons.model.domain.*;
import com.itheima.commons.model.domain.Character;
import com.itheima.commons.model.vo.*;
import com.itheima.dubbo.interfaces.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 测灵魂
 */
@Service
public class TestSoulService {

    @Reference
    private QuestionnaireApi questionnaireApi;

    @Reference
    private SubjectApi subjectApi;

    @Reference
    private SubjectOptionApi subjectOptionApi;

    @Reference
    private UserQuestionnaireApi userQuestionnaireApi;

    @Reference
    private CharacterApi characterApi;

    @Reference
    private UserInfoApi userInfoApi;

    /**
     * 测灵魂的问卷调查
     *
     * @return
     */
    public List<QuestionnaireVo> getQuestionnaire() {
        List<QuestionnaireVo> questionnaireVos = new ArrayList<>();

        //获取用户id，将三个问卷遍历
        List<Questionnaire> questionnaireList = questionnaireApi.findAll();
        // 根据userid，获取用户答题进度，到tb_user_questionnaire表中获取该用户的该问卷是否开锁
        List<Long> id = CollUtil.getFieldValues(questionnaireList, "id", Long.class);
        List<UserQuestionnaire> userQuestionnaires = userQuestionnaireApi.queryByUserId(UserThreadLocal.getUserId());
        //如果查不到，即该用户还没有答过题，存入tb_user_questionnaire表中该用户的初级表为开启状态,其他表为锁
        if (CollUtil.isEmpty(userQuestionnaires)) {
            UserQuestionnaire userQuestionnaire = new UserQuestionnaire();
            userQuestionnaire.setUserId(UserThreadLocal.getUserId());
            for (Long qid : id) {
                userQuestionnaire.setQid(qid);
                if (qid == 1) {
                    userQuestionnaire.setIsLock(0);
                } else {
                    userQuestionnaire.setIsLock(1);
                }
                userQuestionnaire.setScore(0L);
                userQuestionnaireApi.save(userQuestionnaire);
            }
            //重新赋值
            userQuestionnaires = userQuestionnaireApi.queryByUserId(UserThreadLocal.getUserId());
        }
        //用户的答题进度  qid为键
        Map<Long, UserQuestionnaire> qid = CollUtil.fieldValueMap(userQuestionnaires, "qid");

        for (Questionnaire questionnaire : questionnaireList) {
            Integer isLock = qid.get(questionnaire.getId()).getIsLock();
            //获取题目信息
            List<Subject> subject = subjectApi.querySubjects(questionnaire.getId());
            //变成题目的vo对象
            List<SubjectVo> questions = new ArrayList<>();
            for (Subject s : subject) {
                //根据题目id获取题目的选项
                List<SubjectOption> subjectOptions = subjectOptionApi.querySubjectOption(s.getId());
                List<SubjectOptionVo> question = new ArrayList<>();
                for (SubjectOption subjectOption : subjectOptions) {
                    question.add(new SubjectOptionVo(subjectOption));
                }
                questions.add(new SubjectVo(s, question));
            }

            questionnaireVos.add(new QuestionnaireVo(questionnaire, questions, isLock));
        }
        return questionnaireVos;
    }

    /**
     * [PostSubjectOptionVo(questionId=1, optionId=1),
     * *  PostSubjectOptionVo(questionId=2, optionId=5),
     * *  PostSubjectOptionVo(questionId=3, optionId=11),
     * *  PostSubjectOptionVo(questionId=4, optionId=15)]
     * 将用户填的表信息存起来
     *
     * @param answers
     */
    public String saveResults(List<PostSubjectOptionVo> answers) {


        //将题目集合变成以题目id为键的map
        Map<String, PostSubjectOptionVo> questionId = CollUtil.fieldValueMap(answers, "questionId");
        PostSubjectOptionVo postSubjectOptionVo = answers.get(0);
        //通过用户的题目，判断哪个卷子
        Subject subject = subjectApi.querySubjectsById(Convert.toLong(postSubjectOptionVo.getQuestionId()));
        //统计用户得分
        Long score = 0L;
        for (PostSubjectOptionVo answer : answers) {
            SubjectOption subjectOption = subjectOptionApi.queryBySid(Convert.toLong(answer.getOptionId()));
            score = score + subjectOption.getFraction();
        }

        //根据分数判断
        //将用户的分数更新
        userQuestionnaireApi.updataScore(UserThreadLocal.getUserId(), subject.getQid(), score);


        //将现在卷子的id+1，判断是否存在，存在的话就解锁
        if (ObjectUtil.isNotEmpty(userQuestionnaireApi.queryByQid(UserThreadLocal.getUserId(), subject.getQid() + 1))) {
            //该卷子存在，将该卷子解锁
           UserQuestionnaire userQuestionnaire = new UserQuestionnaire(UserThreadLocal.getUserId(),subject.getQid() + 1,0,0,0);
            userQuestionnaireApi.updataIsLock(userQuestionnaire);

        }

        //用户成绩放Character中查询在区间对象
        Character character = characterApi.queryByScore(score);
        //将该卷对应的性格存入UserQuestionnaire中



        UserQuestionnaire userQuestionnaire = new UserQuestionnaire();
        userQuestionnaire.setUserId(UserThreadLocal.getUserId());
        userQuestionnaire.setQid(subject.getQid());
        userQuestionnaire.setIsLock(0);
        userQuestionnaire.setScore(score);
        userQuestionnaire.setCharacterId(character.getId());
        userQuestionnaireApi.updataConclusionId(userQuestionnaire);

        return subject.getQid().toString();
    }

    /**
     * 测灵魂的查看结果
     *
     * @param id
     * @return
     */
    public CharacterVo viewResults(Long id) {

        //查看用户的成绩
        UserQuestionnaire userQuestionnaire = userQuestionnaireApi.queryByQid(UserThreadLocal.getUserId(), 1L);

        //根据性格id查性格表
        Character character = characterApi.queryById(userQuestionnaire.getCharacterId());

        //维度直接用
        List<Dimensions> dimensions = new ArrayList<>();
        //获取所以类型,根据用户的成绩，计算百分比
        List<Character> characters = characterApi.fandAll();
        for (Character character1 : characters) {
            //
            if(userQuestionnaire.getCharacterId()==character1.getId()){
                dimensions.add(new Dimensions(character1.getDimensionsKey(),"90%"));
            }else{
                dimensions.add(new Dimensions(character1.getDimensionsKey(),"80%"));
            }
        }

        //将同卷同是该类型的人筛选出来,排除自己
        List<UserQuestionnaire> userQuestionnaires = userQuestionnaireApi.queryAllByCharacterId(UserThreadLocal.getUserId(),userQuestionnaire.getQid(),userQuestionnaire.getCharacterId());
        //同类型用户的id
        List<Long> userIds = CollUtil.getFieldValues(userQuestionnaires, "userId", Long.class);
        //获取用户头像
        Map<Long, UserInfo> byUserIds = userInfoApi.findUserInfoListByUserIds(userIds);
        List<UserInfoSoulVo> userInfoVos = new ArrayList<>();
        for (Long userId : userIds) {
            userInfoVos.add(new UserInfoSoulVo(byUserIds.get(userId)));
        }

        return new CharacterVo(character, dimensions,userInfoVos);
    }
}
